<template>
  <div class="table-container">
    <!-- 搜索区域 - 使用网格布局实现更灵活的排列 -->
    <div class="search-container">
      <div class="search-fields">
        <el-input
            v-model="inputId"
            size="large"
            placeholder="请输入搜索内容的ID"
            :suffix-icon="Search"
            @change="handleChange"
        />
        <el-input
            v-model="inputName"
            size="large"
            placeholder="请输入搜索内容的名称"
            :suffix-icon="Search"
            @change="handleChangeName"
        />
      </div>
    </div>

    <!-- 按钮和筛选区域 - 整体用弹性布局，内部按功能分组布局 -->
    <div class="button-group">
      <div class="action-buttons">
        <el-button type="primary" v-if="props.formType==='Student'" @click="handleDelete">删除</el-button>
        <el-button type="success" @click="handleAdd">添加</el-button>
        <el-button type="primary">EXCEL导入</el-button>
        <el-button type="success">EXCEL导出</el-button>
      </div>

      <div class="filter-group">
        <el-form-item label="学院" v-if="props.formType==='Student'|| props.formType==='Teacher'|| props.formType==='Major'|| props.formType==='Class'">
          <el-select
              v-model="collegeId"
              filterable
              placeholder="Select"
              @change="changeOptions"
          >
            <el-option
                v-for="item in collegeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" v-if="props.formType==='Student'|| props.formType==='Class'">
          <el-select
              v-model="majorId"
              filterable
              placeholder="Select"
              @change="changeMajor"
          >
            <el-option
                v-for="item in majorOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班级" v-if="props.formType==='Student'">
          <el-select
              v-model="classId"
              filterable
              placeholder="Select"
              @change="classChange"
          >
            <el-option
                v-for="item in classOptions"
                :key="item.name"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
    </div>

    <!-- 表格区域 - 容器设置宽度和溢出处理，表格自适应宽度 -->
    <div class="table-wrapper">
      <el-table :data="data" border @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection"/>
        <el-table-column
            v-for="item in props.title"
            :key="item.propName"
            :prop="item.propName"
            :label="item.name"
            align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index)">编辑</el-button>
            <el-button type="primary" size="small" @click="handleSearch(scope.$index)">查看更多</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 - 用弹性布局实现居中显示 -->
    <div class="pagination-container">
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="dataLength">
      </el-pagination>
    </div>
  </div>

  <!-- 对话框保持不变 -->
  <el-dialog v-model="formVisible" title="编辑" width="500" destroy-on-close @close="handleClose">
    <StudentFormComponent v-if="formType==='Student'" @visible="handleDialogCancel" type="edit"/>
    <CollegeFormComponent v-if="formType==='College'" @visible="handleDialogCancel" type="edit" />
    <ClassFormComponent v-if="formType==='Class'" @visible="handleDialogCancel" type="edit" />
    <MajorFormComponent v-if="formType==='Major'" @visible="handleDialogCancel" type="edit" />
    <TeacherFormComponent v-if="formType==='Teacher'" @visible="handleDialogCancel" type="edit" />
    <CourseFormComponent v-if="formType==='Course'" @visible="handleDialogCancel" type="edit" />
  </el-dialog>

  <el-dialog v-model="addVisible" title="添加" width="500" destroy-on-close @close="handleClose">
    <StudentFormComponent v-if="formType==='Student'" @visible="handleDialogCancel" type="add" />
    <CollegeFormComponent v-if="formType==='College'" @visible="handleDialogCancel" type="add" />
    <ClassFormComponent v-if="formType==='Class'" @visible="handleDialogCancel" type="add"/>
    <MajorFormComponent v-if="formType==='Major'" @visible="handleDialogCancel" type="add" />
    <TeacherFormComponent v-if="formType==='Teacher'" @visible="handleDialogCancel" type="add" />
    <CourseFormComponent v-if="formType==='Course'" @visible="handleDialogCancel" type="add" />
  </el-dialog>

  <el-dialog v-model="showVisible" title="查看更多" width="500" destroy-on-close>
    <StudentFormComponent v-if="formType==='Student'" @visible="handleDialogCancel" type="search" />
    <CollegeFormComponent v-if="formType==='College'" @visible="handleDialogCancel" type="search" />
    <ClassFormComponent v-if="formType==='Class'" @visible="handleDialogCancel" type="search" />
    <MajorFormComponent v-if="formType==='Major'" @visible="handleDialogCancel" type="search" />
    <TeacherFormComponent v-if="formType==='Teacher'" @visible="handleDialogCancel" type="search" />
    <CourseFormComponent v-if="formType==='Course'" @visible="handleDialogCancel" type="search" />
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref, watch} from "vue";
import ClassFormComponent from "@/components/form/ClassFormComponent.vue";
import StudentFormComponent from "@/components/form/StudentFormComponent.vue";
import CollegeFormComponent from "@/components/form/CollegeFormComponent.vue";
import MajorFormComponent from "@/components/form/MajorFormComponent.vue";
import TeacherFormComponent from "@/components/form/TeacherFormComponent.vue";
import CourseFormComponent from "@/components/form/CourseFormComponent.vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/requests/request.js";
import {idStores} from "@/stores/stores.js";
import {ElMessage} from "element-plus";
const props = defineProps({
  title: Array,
  url: {
    deleteUrl: String,
    editUrl: String,
    showUrl: String,
    getCountUrl: String,
    searchUrl: String,
  },
  formType: String
});
const data = ref([]);
const showVisible = ref(false);
const formVisible = ref(false);
const addVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const inputId = ref('');
const inputName = ref('');
const dataLength = ref(0);
const screening = ref(false);
const collegeOptions = ref([])
const majorOptions = ref([])
const classOptions = ref([])
const collegeId = ref('')
const majorId = ref('')
const classId = ref('')
const selectList = ref([]);

onMounted(() => {
  request.get('/college/get-college-tree').then(res => {
    collegeOptions.value = res.data.data
    collegeOptions.value.push({
      id: '',
      name: '全部',
      children: []
    })
  })
  request.get(props.url.showUrl, {
    params: {
      start: 0
    }
  }).then(res => {
    console.log(res.data.data)
    data.value = res.data.data
    console.log(data.value)
  }).catch(err => {
    console.log(err)
  })
  request.get(props.url.getCountUrl).then(res => {
    console.log(res.data.data)
    dataLength.value = res.data.data
  }).catch(err => {
    console.log(err)
  })
})

const store = idStores()
const handleEdit = (index) => {
  console.log('编辑' + index);
  formVisible.value = true;
  store.id = data.value[index].id
};
const handleAdd = (row) => {
  console.log('添加', row);
  addVisible.value = true;
};
const handleSelectionChange = (val) => {
  selectList.value = []
  for (let i = 0; i < val.length; i++) {
    selectList.value.push(val[i].id)
  }
  console.log(selectList.value)
}
const handleDelete = (row) => {
  console.log(data.value[row - 1])
  request.get('/student/delete-student', {
    params: {
      id: selectList.value.join(',')
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getSearch(currentPage.value)
    }
  })
};

const handleSearch = (index) => {
  console.log('查看更多', index);
  showVisible.value = true;
  store.id = data.value[index].id
};

const handleDialogCancel = (visible) => {
  formVisible.value = visible;
  showVisible.value = visible;
  addVisible.value = visible;
  console.log('cancel', visible);
};
const getAll = (page) => {
  request.get(props.url.showUrl, {
    params: {
      start: (page - 1) * 10,
    }
  }).then(res => {
    console.log(res.data.data)
    data.value = res.data.data
    console.log(data.value)
  }).catch(err => {
    console.log(err)
  })
}
const getSearch = (page) => {
  request.post(props.url.searchUrl, {
    id: inputId.value,
    start: (page - 1) * 10,
    collegeId: collegeId.value,
    majorId: majorId.value,
    classId: classId.value,
    name: inputName.value,
  }).then(res => {
    console.log(res.data.data)
    data.value = res.data.data['DATA']
    dataLength.value = Number(res.data.data['COUNT'])
    console.log(dataLength.value)
    console.log(data.value)
  }).catch(err => {
    console.log(err)
  })
}
const handlePageChange = (page) => {
  currentPage.value = page;
  if (screening.value) {
    getSearch(page);
  }
  else {
    getAll(page);
  }
};
const handleChange = () => {
  inputName.value = ''
  collegeId.value = ''
  classId.value = ''
  majorId.value = ''
  if (inputId.value==='') {
    request.get(props.url.getCountUrl).then(res => {
      dataLength.value = res.data.data
    }).catch(err => {
      console.log(err)
    })
    currentPage.value = 1;
    getAll(currentPage.value);
    screening.value = false;
  }
  else {
    currentPage.value = 1;
    getSearch(currentPage.value);
    screening.value = true;
  }
}
const changeOptions = async (value) => {
  console.log(value)
  inputName.value = ''
  inputId.value = ''
  majorId.value = ''
  classId.value = ''
  majorOptions.value = []
  console.log(collegeOptions.value)
  majorOptions.value = collegeOptions.value.find(item => item.id === value).children
  currentPage.value = 1
  if (collegeId.value === '') {
    request.get(props.url.getCountUrl).then(res => {
      dataLength.value = res.data.data
    }).catch(err => {
      console.log(err)
    })
    screening.value = false
    getAll(currentPage.value)
  }
  else {
    screening.value = true
    getSearch(currentPage.value)
  }
  console.log(majorOptions.value)
}
const changeMajor = async (value) => {
  console.log(value)
  currentPage.value = 1
  inputName.value = ''
  inputId.value = ''
  classId.value = ''
  classOptions.value = []
  classOptions.value = majorOptions.value.find(item => item.id === value).children
  if (collegeId.value === '') {
    screening.value = false
    getAll()
  }
  else {
    screening.value = true
    getSearch(currentPage.value)
  }

}
const classChange = (value) => {
  currentPage.value = 1
  inputName.value = ''
  inputId.value = ''
  if (collegeId.value === '') {
    screening.value = false
    getAll()
  }
  else {
    screening.value = true
    getSearch(currentPage.value)
  }
}
const handleChangeName = () => {
  inputId.value = '';
  collegeId.value = ''
  classId.value = ''
  majorId.value = ''
  if (inputName.value==='') {
    request.get(props.url.getCountUrl).then(res => {
      dataLength.value = res.data.data
    }).catch(err => {
      console.log(err)
    })
    currentPage.value = 1;
    getAll(currentPage.value);
    screening.value = false;
  }
  else {
    currentPage.value = 1;
    getSearch(currentPage.value);
    screening.value = true;
  }
}
const handleClose = () => {
  request.get(props.url.showUrl, {
    params: {
      start: (currentPage.value - 1) * 10,
    }
  }).then(res => {
    console.log(res.data.data)
    data.value = res.data.data
    console.log(data.value)
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style scoped>
/* 基础容器 - 使用弹性布局，实现整体的垂直排列和间距控制 */
.table-container {
  padding: clamp(1rem, 3vw, 2rem);
  background-color: #f5f7fa;
  border-radius: 0.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: clamp(1rem, 2vw, 1.5rem);
  min-width: 300px; /* 设置最小宽度，避免过度缩小 */
  width: 85vw;
  box-sizing: border-box; /* 确保内边距等不影响整体宽度 */
}

/* 搜索区域 - 使用网格布局，让输入框自适应且可灵活排列 */
.search-container {
  width: 100%;
}

.search-fields {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: clamp(0.5rem, 1vw, 1rem);
}

/* 按钮组 - 外层弹性布局控制整体排列，内部分组用不同方式布局 */
.button-group {
  display: flex;
  flex-direction: column;
  gap: clamp(1rem, 2vw, 1.5rem);
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: clamp(0.5rem, 1vw, 1rem);
}

.filter-group {
  display: flex;
  flex-wrap: wrap;
  gap: clamp(0.5rem, 1vw, 1rem);
  align-items: center;
}

/* 针对小屏幕设备，优化筛选组的布局 */
@media (max-width: 768px) {
  .filter-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .el-form-item {
    width: 100%;
  }

  .el-select {
    width: 100% !important;
  }
}
</style>
